package com.jch.windowapi;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class CountWindow {

    public static void main(String[] args) throws Exception{

        //创建环境变量
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //获取数据源
        //DataStreamSource<String> source = env.socketTextStream("hadoop101", 44444);
        DataStreamSource<String> source = env.readTextFile("D:\\ideawenjian\\1019\\data\\data.txt");


        //格式化数据
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] split = s.split("\t");
                for (String word : split) {
                    collector.collect(new Tuple2<>(word, 1));
                }
            }
        });

        //数量窗口滑动
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = flatMap.keyBy(0)
                .countWindow(5L, 3L)
                .sum(1);

        //打印
        sum.print();

        //执行
        env.execute();


    }



}
